package com.qiall.boot.userservice.Impl.organization.activity;

import com.qiall.boot.userservice.data.entity.OrganizationInfo;
import com.qiall.boot.userservice.data.entity.UserQueryBean;
import com.qiall.boot.userservice.data.mapper.OrganizationInfoMapper;
import com.qiall.boot.userservice.data.mapper.UserMapper;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.ResultCode;
import com.qiall.common.request.BaseActivity;
import com.qiall.common.request.BaseResponse;
import com.qiall.common.request.GetByIdRequest;
import com.qiall.date.DatetimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class DeleteOrgCheckActivity extends BaseActivity<GetByIdRequest, BaseResponse> {
    @Autowired
    private OrganizationInfoMapper organizationInfoMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void handler(GetByIdRequest request, BaseResponse response) {
        // 校验是否有子组织
        OrganizationInfo queryBean = new OrganizationInfo();
        queryBean.setParentId(request.getId());
        int count = organizationInfoMapper.count(queryBean, "1991-01-01 10:00:00", DatetimeUtils.date2string(new Date(), DatetimeUtils.YYYY_MM_DD_HH_MM_SS));
        if (count > 0) {
            throw new BusinessException(ResultCode.PARAM_IS_INVALID, "存在子节点无法删除");
        }
        UserQueryBean userQueryBean = new UserQueryBean();
        userQueryBean.setOrgId(request.getId());
        int userCount = userMapper.count(userQueryBean);
        if (userCount > 0) {
            throw new BusinessException(ResultCode.PARAM_IS_INVALID, "该组织下存在用户无法删除");
        }
    }
}
